/**
 * 
 */
ProfileInformationPortlet = Class.extend({
	init: function()	{
		this.subject = SingletonFactory.getInstance(Subject);
		this.name = 'ProfileInformationPortlet';
		this.profile_id = undefined;
	},
	
	onReloadPage: function()	{
		//console.log('page is reloaded');
		this.run();
	},
	
	onBegin: function()	{
		this.registerObserver();
		this.buildTemplate();
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var profileId = this.getRequest().getParam('id', undefined);
		var obj = this;
		this.onAjax('ajax', 'get-profile-detail', {'id':profileId}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.onGetProfileDetailSuccess(ret);
				},
				'onFailure': function(message)	{
//					var subject = SingletonFactory.getInstance(Subject);
//					var request = new Request("ErrorPage","",{"code":"888", "msg":"Lỗi","content":"Không tìm thấy profile"}); 
//					subject.notifyEvent('RequestRoute', request);
					//obj.getPortletPlaceholder().paintCanvas('Profile không tồn tại');
					
					//redirect to error page
					var request = new Request('ErrorPage', undefined, {'code':404});
					var subject = SingletonFactory.getInstance(Subject);
					subject.notifyEvent('RequestRoute', request);
				}}, true, 1800000);
	},
	
	onGetProfileDetailSuccess: function(ret)	{
		this.getPortletPlaceholder().paintCanvas(this.requestForResource('ViewData').html());
		var data = ret.data;
		this.profile_id = ret.profile_id;
		var stack = Array();
		for(var i=0;i<data.length;i++)	{
			data[i].depth = 0;
			stack.push(data[i]);
		}
		if (data.length>0)	{	
			while(stack.length > 0)	{
				var current = stack.pop();
				this.processNode(current);
				if (typeof current.children != 'undefined')	{
					for(var i=0;i<current.children.length;i++)	{
						var child = current.children[i];
						child.depth = current.depth+1;
						stack.push(child);
					}
				}
			}
			this.finishRendering();
		}
	},
	
	finishRendering: function()	{
		var id = this.getRequest().getParam('id');
		if (id == undefined)	{
			this.getPortletPlaceholder().getCanvas().access().find('h1').hide();
		}
		this.subject.notifyEvent("NeedFormatting");
	},
	
	processNode: function(current)	{
		if (current.keyword == 'full_name')	{
//			this.requestForEffectiveResource('ProfileName').html(current.content);
//			SingletonFactory.getInstance(Application).getSystemProperties().set('profile.current.name', current.content);
		} else {
			this.renderPlaceholder(current);
		}
	},
	
	buildTemplate: function()	{
		var rootNode = this.requestForResource('ProfileStructure');
		var placeholder = this.requestForResource('ProfileMainContent');
		this.subject.notifyEvent('BuildProfileTemplate', {'id': this.name, 'root':rootNode, 'placeholder': placeholder});
	},
	
	onShareButtonClick: function(e)	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedLogin');
	},
	
	onLoginSuccess: function()	{
		this.subject.notifyEvent('NeedToggleRelationship');
	},
	
	onNeedToggleRelationship: function()	{
		this.toggle();
	},
	
	toggle: function()	{
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var id = properties.get('user.id');
		//FIXME: (Done) profileId must be retrieved in request parameter 
		var root = properties.get('host.root');
		$('.relationship').slideToggle();
		var obj = this;
		this.onAjax('ajax', 'compare-relationship', {'profile-id':this.profile_id}, 'POST', 
				{'onSuccess': function(ret)	{
					obj.onCompareRelationshipSuccess(ret);
				}});
	},
	
	onCompareRelationshipSuccess: function(ret)	{
		var partial = {};
		partial.result = Array();
		for(i=0;i<ret.length;i++)
		{
			partial.result.push(ret[i]);
		}
		var level = "";
		var mark = (ret.length / 7).toFixed(2);
		if (mark < 0.4) level = this.getLocalizedText('LowRelation');
		else if (mark < 0.65) level = this.getLocalizedText('NormalRelation');
			else if (mark < 0.75) level = this.getLocalizedText('FairRelation');
				else level = this.getLocalizedText('HighRelation');
		var str = this.renderView("ProfileRelationPartial", partial);
		var number = ret.length || 0;
		var summary = this.getLocalizedMessage('RelationSummary', number, level);
		dataObj = {};
		dataObj.content = str;
		dataObj.summary = summary;
		var str = this.renderView("ProfileShareInfo", dataObj);
		$('.relationship').html(str);
	},

	renderPlaceholder: function(current)	{
		this.subject.notifyEvent('RenderPlaceholder', {'node': current, 'callback': 'RenderingDone', 'id': this.name, 'state':'View'});
	},
	
	onRenderingDone: function(eventData)	{
		var html = eventData.html;
		var current = eventData.node;
		var parentChildrenContainerID = current.p_keyword+'Children'+current.p_oid;
		if ($(this.requestForEffectiveResource(parentChildrenContainerID)).length == 0 )	{
//			 //console.log('the children container for '+current.keyword+' not exists('+parentChildrenContainerID+')');
			this.insertAfterPrototype(html, current);
		}
		// otherwise, create new inside the parent's children container
		else {
//			 //console.log('the children container for '+current.keyword+' exists');
			//find the most appropriate sibling
			var siblings = this.requestForMatchingEffectiveResource(parentChildrenContainerID, "[rootname='"+current.keyword+"']:first");
			if (siblings != undefined && siblings.length > 0)	{
//				//console.log('found sibling: '+current.keyword);
				$(html).insertAfter($(siblings));
			} else {
				this.requestForEffectiveResource(parentChildrenContainerID).append(html);
			}
		}
	},
	
	insertAfterPrototype: function(html, current)	{
		$(html).insertAfter(this.requestForEffectiveResource(current.keyword+'Prototype'));
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

ProfileTemplatePlugin = Class.extend({
	init: function()	{
		this.name = "ProfileTemplatePlugin";
		this.nodeTypes = Array();
	},
	
	onBuildProfileTemplate: function(eventData)	{
		var id = eventData.id;
		var rootNode = eventData.root;
		var placeholder = eventData.placeholder;
		
		this.nodeTypes[id] = Array();
		var stack = Array();
		rootNode.depth = 0;
		rootNode.parent = undefined;
		stack.push(rootNode);
		var partialRootObj = {};
		partialRootObj.namespace = id;
		partialRootObj.name = $(rootNode).attr('name');
		partialRootObj.type = $(rootNode).attr('type');
		partialRootObj.params = $(rootNode).attr('params');
		var html = tmpl('TemplatePartial', partialRootObj);
		$(placeholder).html(html);
		while (stack.length>0)	{
			rootNode = stack.pop();
			this.storeNodeDetail(id, rootNode);
			var childrenNode = $(rootNode).children();
			if (rootNode.parent != undefined)	{
				this.buildPrototype(id, rootNode.parent, rootNode);
			}
			for(var i=0;i<childrenNode.length;i++)	{
				var childNode = childrenNode[i];
				childNode.parent = rootNode;
				childNode.depth = rootNode.depth+1;
				stack.push(childNode);
			}
		}
	},
	
	buildPrototype: function(id, rootNode, childNode)	{
		var partialObj = {};
		partialObj.name = $(childNode).attr('name');
		partialObj.type = $(childNode).attr('type');
		partialObj.params = $(childNode).attr('params');
		partialObj.namespace = id;
		var partial = tmpl('TemplatePartial', partialObj);
		$('div[name="'+$(rootNode).attr('name')+'_container_children"]').append(partial);
	},
	
	storeNodeDetail: function(id, rootNode)	{
		var name = $(rootNode).attr('name');
		this.nodeTypes[id][name] = {};
		this.nodeTypes[id][name].type = $(rootNode).attr('type');
		this.nodeTypes[id][name].params = $(rootNode).attr('params');
		this.nodeTypes[id][name].value = $(rootNode).attr('value');
		this.nodeTypes[id][name].parent = rootNode.parent;
		this.nodeTypes[id][name].depth = rootNode.depth-1;
		this.nodeTypes[id][name].singleton = $(rootNode).attr('singleton');
	},
	
	onRenderPlaceholder: function(eventData)	{
		var current = eventData.node;
		var callback = eventData.callback;
		var state = eventData.state;
		var id = eventData.id;
		// build the placeholder
		var obj = {};
		obj.id = current.oid;
		obj.name = current.keyword;
		if (this.nodeTypes[id][obj.name] != undefined)	{
			obj.type = this.nodeTypes[id][obj.name].type;
			obj.params = this.nodeTypes[id][obj.name].params;
		}
		if (typeof obj.type == 'undefined')	{
			// //console.log('object of type '+obj.name+' is undefined');
			return;
		}
		this.nodeTypes[id][obj.name].existed = true;
		var objdata = {};
		objdata.type = obj.type;
		objdata.depth = current.depth;
		objdata.keyword = this.nodeTypes[id][obj.name].value;
		objdata.content = current.content;
		objdata.name = current.keyword;
		objdata.params = obj.params;
		objdata.state = state;
		// //console.log('will create '+obj.type);
		obj.content = tmpl('UnformattedPlaceholder', objdata);
		obj.namespace = id;
		var html = tmpl('ProfilePartial', obj);
		// if the parent is undefined then create new after the prototype
		var parent = this.nodeTypes[id][obj.name].parent;
		if (current.p_keyword != $(parent).attr('name'))	{
			// //console.log('conflict between server and client profile structure
			// ('+current.p_keyword+' and '+$(parent).attr('name')+')');
			current.p_keyword = $(parent).attr('name');
		}
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent(callback, {'node': current, 'html':html});
	},
	
	onBuildMockupNode: function(eventData)	{
		var name = eventData.nodeName;
		var ancestor = eventData.nodeBefore;
		var id = eventData.id;
		var node = this.nodeTypes[id][name];
		//build the mockup node
		var html = this.buildMockupNode(node);
		$("<div class='container'>"+html+"</div>").insertAfter($(ancestor));
	},
	
	buildMockupNode: function(node)	{
		var obj = {};
		obj.depth = node.depth;
		obj.params = node.params;
		obj.type = node.type;
		obj.name = node.name;
		obj.keyword = node.value;
		obj.content = node.value;
		return tmpl('AddNewPlaceholder', obj);
	},	
	
	onDisplayRemainingNodes: function(eventData)	{
		this.displayRemainingNodes(eventData.id);
	},

	buildNodeFromObject: function(namespace, node, id, partialView)	{
		var obj = {};
		obj.id = id;
		obj.name = node.name;
		obj.type = node.type;
		obj.params = node.params;
		var objdata = {};
		objdata.type = node.type;
		objdata.depth = node.depth;
		objdata.keyword = node.value;
		objdata.content = node.value;
		objdata.name = node.name;
		objdata.params = node.params;
		objdata.state = "Edit";
		obj.content = tmpl(partialView, objdata);
		obj.namespace = namespace;
		var html = tmpl('ProfilePartial', obj);
		return html;
	},
	
	displayRemainingNodes: function(id)	{
		for(var name in this.nodeTypes[id])	{
			this.displayRemainingNode(id, name);
		}
		$('div[rootName]').attr('added', 'true');
	},
	
	displayRemainingNode: function(id, name)	{
		var obj = this.nodeTypes[id][name];
		if (obj.singleton !== "true" || obj.existed != true)	{
			obj.name = name;
			var html = "";
			if (obj.singleton !== "true")
				html = this.buildNodeFromObject(id, obj, 'AddNew','AddNewPlaceholder');
			else 	{
				html = this.buildNodeFromObject(id, obj, '', 'UnformattedPlaceholder-Edit');
			}
			var parent = $(obj.parent).attr('name');
			var parentNode = $('div[rootName="'+parent+'"]');
//			//console.log('finding parent '+'div[rootName="'+parent+'"]');
			$(parentNode).each(function(index, value)	{
				if ($(value).attr('added') == 'true')	{
					return;
				}
//				//console.log('found');
				if ($(value).find('div[rootName="'+name+'"]').length > 0)	{
					//existing
					$(html).insertAfter($(value).find('div[rootName="'+name+'"]').last());
				} else {
					$(value).children('.children_container').append(html);
				}
			});
		}
	}
}).implement(PluginInterface);